package com.rc.saas.tenant.mq;

import com.alibaba.fastjson.JSON;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.rc.saas.tenant.common.sms.AliyunSmsUtil;
import com.rc.saas.tenant.common.sms.AliyunSmsTemplateEnum;
import com.rc.saas.tenant.model.sms.TenantSms;
import com.rc.saas.tenant.model.tenant.Tenant;
import com.rc.saas.tenant.service.sms.TenantSmsService;
import com.rc.saas.tenant.service.tenant.TenantService;
import com.rc.saas.tenant.vo.msg.TenantMsgReq;
import com.rabbitmq.client.Channel;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.listener.api.ChannelAwareMessageListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * SMS余量提醒
 */
@Component("smsRemainWarningListener")
public class SmsRemainWarningListener implements ChannelAwareMessageListener {
    private static Logger logger = LogManager.getLogger(SmsRemainWarningListener.class);

    @Autowired
    private TenantService tenantService;

    @Autowired
    private TenantSmsService tenantSmsService;

    @Override
    public void onMessage(Message message, Channel channel) throws Exception {
        String msg = new String(message.getBody(), "UTF-8");
        logger.info("smsRemainWarningListener 收到了:{}", msg);

        TenantMsgReq tenantMsgReq = JSON.parseObject(msg, TenantMsgReq.class);

        TenantSms tenantSms = tenantSmsService.selectByTenantCode(tenantMsgReq.getTenentCode());

        Tenant tenant = tenantService.selectByTenantCode(tenantMsgReq.getTenentCode());
        if (tenantSms!=null){
            if (tenantSms.getAmount()>100){
                //todo 发短信通知
                String code = String.valueOf(tenantSms.getAmount());
                SendSmsResponse sendSmsResponse= AliyunSmsUtil.sendSms(tenant.getPhone(), code, AliyunSmsTemplateEnum.SMS_WARN, tenant.getSmsSign());
                if (sendSmsResponse.getCode().equals("OK")){
                    // 更新sms表
                    tenantSmsService.updateTenantSmsByTenantCode(tenant.getPhone(),tenantMsgReq.getTenentCode(),0l,"0","短信数量警告"+tenant.getPhone(),"短信数量警告");
                }
            }
        }


    }
}
